/**
 * 邮件模板新增编辑页
 */
import React, { useEffect, useRef, useCallback } from 'react';

import { Button, Card, Divider, Form, Input } from 'antd';

import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import { formatResultByFetchDetail, onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import { getDict } from '@/utils/dataDictUtil';
import pageTabUtil from '@/utils/pageTabUtil';
import useFormStorage from '@/hooks/useFormStorage';
import FormStorageStatus from '@/containers/FormStorageStatus';
import EntryTimeChangeMailPreview from './EntryTimeChangeMailPreview';

import { TemplateEditor } from '../components';
import {
    getDefaultConfigByType,
    getEntryTimeChangeMailTemplateDetail,
    saveEntryTimeChangeMailTemplate
} from '../services';
import styles from './index.less';

const EntryTimeChangeMailEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    // const [editorValue, setEditorValue] = React.useState('');
    const [dictList, setDictList] = React.useState([]);
    const [mainData, setMainData] = React.useState({});

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('add');
    }, [location]);

    // 如果是新增的情况，写入默认邮件模板
    const { data: defaultEmailTemplate, run: fetchEmailTemplate } = useRequest(getDefaultConfigByType, {
        manual: true,
        ...defaultFormatResult
    });

    // // 获取通知模板
    const { data, loading, run: fetchTemplate } = useRequest(getEntryTimeChangeMailTemplateDetail, {
        manual: true,
        formatResult: formatResultByFetchDetail
    });

    // 保存面试评估表
    const { loading: saveLoading, run: saveTemplate } = useRequest(saveEntryTimeChangeMailTemplate, {
        manual: true,
        onSuccess: res =>
            onSuccessBySave(res, {
                action: isAddPage ? 'create' : 'edit',
                id: query?.id,
                key: 'EntryTimeChangeMail',
                type: 'rmStorage'
            })
    });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const params = {
                    isDefault: data?.isDefault ?? 0,
                    ...values,
                    entryTimeChangeContent: values.entryTimeChangeContent
                        .replace(/<span data-foo="/g, '${')
                        .replace(/" data-id="[0-9]+" class="column-item">[\u4e00-\u9fa5]+<\/span>/g, '}')
                };
                if (!isAddPage) {
                    params.id = query?.id;
                }
                saveTemplate(params);
            }
        });
    };

    // 获取邮件插入参数数据字典
    useEffect(() => {
        getDict('paramOfEntryTimeChange').then(ret => {
            const dict = ret && ret.map(e => ({ field: e.dictValue, value: e.dictName }));
            setDictList(dict);
        });
    }, []);

    useEffect(() => {
        if (query?.id) {
            fetchTemplate(query?.id);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [query]);

    useEffect(() => {
        if (isAddPage) {
            fetchEmailTemplate(7);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const previewRef = useRef();
    const handlePreview = useCallback(() => {
        previewRef.current.open({ entryTimeChangeContent: form.getFieldValue('entryTimeChangeContent') });
    }, [form]);
    const { formData, status: formStorageStatus, isFirstTimeToPage, saveTime } = useFormStorage({
        form,
        action: isAddPage ? 'create' : 'edit',
        id: query?.id,
        key: 'EntryTimeChangeMail'
    });

    useEffect(() => {
        setMainData(formData || data);
    }, [data, formData]);

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '添加模板' : '编辑模板'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button type="primary" ghost onClick={handlePreview}>
                            预览
                        </Button>
                        <Divider type="vertical" />
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleSubmit} loading={saveLoading}>
                            提交
                        </Button>
                    </BottomAction>
                }
            >
                <FormStorageStatus
                    status={formStorageStatus}
                    isFirstTimeToPage={isFirstTimeToPage}
                    saveTime={saveTime}
                ></FormStorageStatus>
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="模板名称">
                        {getFieldDecorator('settingName', {
                            initialValue: mainData?.settingName,
                            rules: [
                                {
                                    required: true,
                                    message: '请输入模板名称'
                                }
                            ]
                        })(<Input placeholder="请输入模板名称" allowClear maxLength={200} style={{ maxWidth: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="适用行政机构">
                        {mainData?.isDefault === 1 && '全集团'}
                        {mainData?.isDefault === 1 &&
                            form.getFieldDecorator('administrativeScopes', {
                                initialValue: mainData?.administrativeScopes || undefined
                            })(<input type="hidden" />)}
                        {mainData?.isDefault !== 1 &&
                            getFieldDecorator('administrativeScopes', {
                                initialValue: mainData?.administrativeScopes,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择行政机构'
                                    }
                                ]
                            })(
                                <OrganizationSelect
                                    isStrictly
                                    maxTagCount={2}
                                    isNeedPermission={false}
                                    onlyCompany
                                    treeCheckable
                                    style={{ maxWidth: 528 }}
                                />
                            )}
                    </Form.Item>
                    <Form.Item label="邮件主题">
                        {getFieldDecorator('contentTitle', {
                            initialValue: mainData?.contentTitle || '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入邮件主题'
                                }
                            ]
                        })(<Input placeholder="请输入邮件主题" allowClear maxLength={200} style={{ maxWidth: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="邮件正文">
                        {form.getFieldDecorator('entryTimeChangeContent', {
                            rules: [
                                {
                                    required: true,
                                    message: '邮件正文不能为空'
                                }
                            ]
                        })(
                            <TemplateEditor
                                // onChange={handleChange}
                                initialValue={
                                    mainData?.entryTimeChangeContent || defaultEmailTemplate?.entryTimeChangeContent
                                }
                                contentStyle={{ height: 'auto', minHeight: 250 }}
                                insertParamList={dictList} // 要参数的参数由外部引入
                            />
                        )}
                    </Form.Item>
                </Form>
                <EntryTimeChangeMailPreview ref={previewRef} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default React.memo(Form.create()(EntryTimeChangeMailEdit));
